/* -----------------------------------------------------------------------
 *   Copyright (C) 2008 by Denjs
 *   dplsoft@pisem.net
 *   http://qdroid.berlios.de
 * -----------------------------------------------------------------------
 *   This program is free software licensed under GNU GPL License v.2 ; see main.cpp fo details
 *   Эта программа является свободным программным обеспечением; распространяемым под
 *   лицензией GNU General Public License v.2 (УНИВЕРСАЛЬНАЯ ОБЩЕСТВЕННАЯ ЛИЦЕНЗИЯ GNU версия 2.0)
 * ----------------------------------------------------------------------- */
/*
 * t_FunctionRegistryItem.cpp
 *
 *  Created on: 18.11.2008
 *      Author: Denjs
 * v 2009.05.01_2300
 */

#include "t_FunctionRegistryItem.h"

/* ================================================================
*/
t_FunctionRegistryItem::t_FunctionRegistryItem(QObject *parent)
: QObject(parent)
{
}
/* ================================================================
*/
//для контейнер QList
t_FunctionRegistryItem::t_FunctionRegistryItem(const t_FunctionRegistryItem &other)
{
	this->FileName=other.FileName;
	this->Description=other.Description;
	this->Name=other.Name;
	this->ScriptSource=other.ScriptSource;
	this->SettingsFile=other.SettingsFile;
}
/* ================================================================
*/
//для контейнер QList
t_FunctionRegistryItem& t_FunctionRegistryItem::operator=(const t_FunctionRegistryItem &other)
{
	this->FileName=other.FileName;
	this->Description=other.Description;
	this->Name=other.Name;
	this->ScriptSource=other.ScriptSource;
	this->SettingsFile=other.SettingsFile;

	return *this;
}
/* ================================================================
Загрузка скрипта
*/
int t_FunctionRegistryItem::load_from_file(QString _FileName)
{
	QString DBGPlace="t_FunctionRegistryItem::load_from_file()";
	int DebugLevel=1;//0..5 - от "молчим2 до "подробного" отчета

	//QString QDroidScriptString="/*QDroidScript*/";
	QString QDroidScriptString="#!/bin/qdroid";
	QString QDroidScriptString2="#!/usr/bin/qdroid";
	QString QDroidCodePageOption="codepage";
	QString CurrentScriptCodePage="";//


	if (!_FileName.isEmpty())
	  {
		this->FileName = _FileName;
	  };
    //emit std_out("[checkpoint] t_FunctionRegistryItem::load_from_file()::[0049]: try to load file: ["+this->FileName+"]");
    QFile file(this->FileName);
    ScriptSource.clear();

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
			QString Msg="[ERROR] Error while loading file ["+FileName+"]";
			emit std_out( DBGPlace+":[0075]"+Msg);
			if (DebugLevel>=1) qDebug()<<"DBG.L1::"<<DBGPlace<<":[00076]::"<<Msg;
			return -1;
        };


    //qDebug()<<"[][][][]QDir::absoluteFilePath(this->FileName)"<< scriptDir.absoluteFilePath(this->FileName);
    //qDebug()<<"[][][][] cleaned:: "<< scriptDir.cleanPath( scriptDir.absoluteFilePath(this->FileName) ) ;
  


    //if (QDir::Script_DirPath())
    QDir scriptDir;
    this->DirPath= scriptDir.cleanPath( scriptDir.absoluteFilePath(this->FileName) ) ;
    //this->DirPath= scriptDir.cleanPath( scriptDir.absolutePath(this->FileName) ) ;

    //QDir()

    QString Line0=QString().append(file.readLine());
    QString Line1=QString().append(file.readLine());

    //попробуем осознать, что нам подсовывают...
    //TODO анализ и конвертирование кодировки строк
    if ( (Line0.trimmed().toLower()!=QDroidScriptString.toLower())
    	and ((Line0.trimmed().toLower()!=QDroidScriptString2.toLower()))
    	)
      {
    	QString Msg="[WARNING!] seems it is not QtDroid script.";
    	emit std_out( DBGPlace+":[0089]"+Msg);
		if (DebugLevel>=3) qDebug()<<"DBG.L3::"<<DBGPlace<<":[0089]::"<<Msg;
      };
    Line1=Line1.trimmed();
//    if (Line1.startsWith("/*")) Line1=Line1.mid(2);//отсечем комментарий
//    if (Line1.endsWith("*/")) Line1.chop(2);//отсечем окончание комментария
    if (Line1.startsWith("#")) Line1=Line1.mid(1);//отсечем комментарий
    if (Line1.endsWith(";")) Line1.chop(1);//отсечем окончание комментария

    QStringList ScriptOptionList=Line1.split(";");// пока будем считать что в строке одна опция
    QStringList VarValue=ScriptOptionList.at(0).split("=");//пока анализируем первый
    if (VarValue.at(0).toLower()==QDroidCodePageOption.toLower())
    	CurrentScriptCodePage=VarValue.at(1);

    QString DefaultCodePage="Windows-1251";
    if (CurrentScriptCodePage.trimmed().isEmpty())
     {
		QString Msg="[WARNING] Codepage load-directive does not included. Using Default codepage: ["+DefaultCodePage+"]";
		emit std_out(DBGPlace+":[0108]"+Msg);
		if (DebugLevel>=2) qDebug()<<"DBG.L2::"<<DBGPlace<<":[0108]::"<<Msg;
    	CurrentScriptCodePage=DefaultCodePage;//emit std_out("[NOTE!] t_FunctionRegistryItem::load_from_file()::[0077]: codepage ["+CurrentScriptCodePage+"]does not supported yet.");
     };
    QTextCodec *Codec = QTextCodec::codecForName(CurrentScriptCodePage.toAscii());
    if (Codec==NULL)
     {
		QString Msg="[WARNING] Codepage ["+CurrentScriptCodePage+"] specify in script-file does not supported. Using Default codepage: ["+DefaultCodePage+"]";
		emit std_out(DBGPlace+":[0116]"+Msg);
		if (DebugLevel>=2) qDebug()<<"DBG.L2::"<<DBGPlace<<":[0117]::"<<Msg;
    	Codec = QTextCodec::codecForName(DefaultCodePage.toAscii()); //
     };

    QByteArray line;
    //и загрузим оставшуюся часть скрипта.
    file.reset();
    while (!file.atEnd())
		{
			line = file.readLine();
			if (DebugLevel>=5) qDebug()<<"DBG.L3::"<<DBGPlace<<":[0112]:: ScriptDump:"<<line;
			ScriptSource.append(QString().append(Codec->toUnicode(line)));
		};
    QString Msg="[OK] script loaded from file: ["+FileName+"]";
  	//emit std_out(DBGPlace+":[0125]"+Msg);
	if (DebugLevel>=3) qDebug()<<"DBG.L3::"<<DBGPlace<<":[0125]::"<<Msg;

    return 0;
}
/*
supported codepages:
Apple Roman
Big5
Big5-HKSCS
EUC-JP
EUC-KR
GB18030-0
IBM 850
IBM 866
IBM 874
ISO 2022-JP
ISO 8859-1 to 10
ISO 8859-13 to 16
Iscii-Bng, Dev, Gjr, Knd, Mlm, Ori, Pnj, Tlg, and Tml
JIS X 0201
JIS X 0208
KOI8-R
KOI8-U
MuleLao-1
ROMAN8
Shift-JIS
TIS-620
TSCII
UTF-8
UTF-16
UTF-16BE
UTF-16LE
UTF-32
UTF-32BE
UTF-32LE
Windows-1250 to 1258
WINSAMI2
*/
/* ================================================================
*/
int t_FunctionRegistryItem::save_to_file(QString FileName)
{
	//TODO save_to_file() t_FunctionRegistryItem
    emit std_out("[stopper] t_FunctionRegistryItem::save_to_file()::[0046]: File name: ["+FileName+"]");
}


/* ======== ========================================================
 инициировать исполнение скрипта.
 фактически приводит к испусканию сигнала script_to_be_executed()
*/
int t_FunctionRegistryItem::init_execution()
{
    //emit std_out("[stopper] t_FunctionRegistryItem::init_execution()::[0057]: Signal Resived");
    load_from_file("");//перезагрузим скрипт из файла
    emit script_to_be_executed(ScriptSource);
    return 0;
}

